# -*- coding: UTF-8 -*- 
from xml.etree import ElementTree as ET
import urllib2, time
from deal_info_api import *

def deal_info_time(f_xml, deal, li_from, li_to, tabsum):
    ut = time.gmtime(time.time() + 28800)

    t = '%Y-%m-%d %X'

    f_xml.write(('\t' * tabsum + '<start_time>%s+0800</start_time>\n' % (time.strftime(t, ut))).encode('utf-8'))

    deal_end_time = deal.getiterator(li_from)
    
    f_xml.write(('\t' * tabsum + '<%s>%s+0800</%s>\n' % (li_to, deal_end_time[0].text, li_to)).encode('utf-8'))

def deal_city(tuan, city):
    (f_id, d_id, orig) = judge_begin(tuan, city)

    f_url = urllib2.urlopen('http://www.cocotuan.com/api/cocotuan.asmx/GetTodayProductsWithoutFullDescriptionByCity?cityName=%s' % (city))

    root_url = ET.fromstring(f_url.read())
    
    f_xml = open('%sxml/%s_%s.xml' % (get_home_dir(), tuan, city), 'w')

    f_xml.write('<deals>\n')

    deals = root_url.getiterator('{http://www.cocotuan.com/}' + 'Product')
    for deal in deals:
	if judge(f_id, d_id, deal, '{http://www.cocotuan.com/}' + 'Url'):
	    continue

	f_xml.write('\t' + '<deal>\n')
	deal_info_source(f_xml, 'cocotuan', '可可团'.decode('utf-8'), 'http://www.cocotuan.com/', 'http://www.cocotuan.com/')
	f_xml.write('\t' * 2 + '<city>%s</city>\n' % city)

	deal_info_add(f_xml, deal, '{http://www.cocotuan.com/}Url', 'id', 2)
	deal_info_add(f_xml, deal, '{http://www.cocotuan.com/}Name', 'name', 2)
	deal_info_cats(f_xml, deal, '{http://www.cocotuan.com/}Name')
	deal_info_vendor_2(f_xml)
	deal_info_time(f_xml, deal, '{http://www.cocotuan.com/}AlertTime', 'end_time', 2)
	deal_info_add(f_xml, deal, '{http://www.cocotuan.com/}MarketPrice', 'o_price', 2)
	deal_info_add(f_xml, deal, '{http://www.cocotuan.com/}LocalPrice', 'c_price', 2)
	deal_info_discount_and_save_money(f_xml, deal, '{http://www.cocotuan.com/}LocalPrice', '{http://www.cocotuan.com/}MarketPrice')
	deal_info_add(f_xml, deal, '{http://www.cocotuan.com/}Picture', 'img', 2)
	deal_info_add(f_xml, deal, '{http://www.cocotuan.com/}Url', 'url', 2)

	f_xml.write('\t' + '</deal>\n')

    f_xml.write(orig[8 : ])

    f_xml.close()
    f_id.close()

    judge_end(tuan, city)



f_city = urllib2.urlopen('http://www.cocotuan.com/api/cocotuan.asmx/GetOpenedCities')
root_city = ET.fromstring(f_city.read())
city_id = root_city.getiterator('{http://www.cocotuan.com/}CityID')
for node in city_id:
    deal_city('cocotuan', node.text.lower())
